/*
 * @Author: yuxt
 * @Date: 2024-05-20 09:19:14
 * @LastEditTime: 2024-05-30 18:38:01
 * @LastEditors: yuxt
 * @Description: 
 */
import NextAuth from 'next-auth';
import { authConfig } from '@/server/auth/config';
import { NextRequest, NextResponse } from "next/server";
import { locales } from '@/lib/i18n/config';

// import createMiddleware from "next-intl/middleware";
// import { defaultLocale, localePrefix, locales } from '@/i18n/config';

// const intlMiddleware = createMiddleware({
//   locales,
//   localePrefix,
//   defaultLocale,
//   localeDetection: false
// });

// export default intlMiddleware;

// const authMiddleware = NextAuth(authConfig).auth((req) => {
//   return intlMiddleware(req)
// });

const authMiddleware = NextAuth(authConfig).auth;

const isPublicPage = (pathname: string) => {
  // 不需要授权、公开的页面
  const whitePages = [
    "/",
    "/hello",
    "/chat",
    "/chat/structured_output",
    "/chat/retrieval",
    "/chat/agents",
    "/flowise",
    "/flowise/canvas",
  ]
  const regex = RegExp(`^(/(${locales.join("|")}))?(${whitePages.flatMap((p) => (p === "/" ? ["", "/"] : p)).join("|")})/?$`, "i")
  return regex.test(pathname);
}

export default async function middleware(req: NextRequest, res: any) {
  const { pathname } = req.nextUrl;
  // 调用是API接口
  if (["/api"].some((prefix) => pathname.startsWith(prefix))) {
    return NextResponse.next();
  }
  if (isPublicPage(pathname)) {
    return NextResponse.next();
  }
  return (authMiddleware as any)(req);
}

export const config = {
  // https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher
  matcher: ['/((?!api|_next/static|_next/image|img/|favicon.ico|.*\\.png|.*\\.pdf$).*)'],
};
